package com.hcloud.auth.sms;

import com.hcloud.auth.config.SecurityConstants;
import com.hcloud.common.sms.exception.WrongSmsCodeException;
import com.hcloud.common.sms.validate.SmsCodeValidate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验验证码的过滤器
 *
 * @author hepangui
 * @date 2018-12-13
 */
@Slf4j
@Component("SmsCodeFilter")
@AllArgsConstructor
public class SmsCodeFilter extends OncePerRequestFilter {  //接口的目的是为了在其他参数都组装完毕以后去初始化urls的值

    /**
     * 自定义的认证失败处理器
     */
    private final AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String requestURI = request.getRequestURI();
        if (requestURI.indexOf(SecurityConstants.LOGIN_MOBILE) > -1) {
            log.info("校验请求(" + requestURI + ")中的短信验证码");
            var result = SmsCodeValidate.validateSmsCode(request);
            if (result) {
                log.info("验证码校验通过");
            } else {
                authenticationFailureHandler.onAuthenticationFailure(request, response, new WrongSmsCodeException("短信吗校验失败"));
                return;
            }
        }
        chain.doFilter(request, response);

    }

}
